package com.huluobo.high3demo.video;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.huluobo.high3demo.R;
import com.huluobo.high3demo.adapter.CommentAdapter;
import com.huluobo.high3demo.adapter.MutableReCommendAdapter;
import com.huluobo.high3demo.databinding.FragmentReCommondBinding;
import com.huluobo.high3demo.live.LiveActivity;
import com.huluobo.mvvm.baen.CommentBeanResult;
import com.huluobo.mvvm.baen.FollowLikeBeanResult;
import com.huluobo.mvvm.baen.VideoBeanResult;
import com.huluobo.mvvm.view.BaseMVVMFragment;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.ArrayList;
import java.util.List;

public class ReCommendFragment extends BaseMVVMFragment<FragmentReCommondBinding, VideoViewModel> {

    private int currentPage = 1;
    private int pageSize = 10;

    //当前播放的是哪个视频的下标
    private int currentPosition = 0;

    private List<VideoBeanResult.VideoBean> videoBeanList = new ArrayList<>();
    //    private ReCommendAdapter adapter;
    private MutableReCommendAdapter adapter;
    private CommentAdapter commentAdapter;

    private StandardGSYVideoPlayer player;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_re_commond;
    }

    @Override
    protected void initData() {
        viewModel.getVideoList(1, 10);

        viewModel.success.observe(requireActivity(), new Observer<VideoBeanResult>() {
            @Override
            public void onChanged(VideoBeanResult videoBeanResult) {
//                videoBeanList.addAll(videoBeanResult.getData());
                adapter.getData().addAll(videoBeanResult.getData());
                adapter.notifyDataSetChanged();
            }
        });

        viewModel.followAuthSuccess.observe(requireActivity(), new Observer<FollowLikeBeanResult>() {
            @Override
            public void onChanged(FollowLikeBeanResult followLikeBeanResult) {
                ToastUtils.showLong("关注成功");
                //更新数据
                adapter.getData().get(currentPosition).setGuanzhu(1);
                //单独刷新适配器
                adapter.notifyItemChanged(currentPosition);
            }
        });

        viewModel.likeSuccess.observe(requireActivity(), new Observer<FollowLikeBeanResult>() {
            @Override
            public void onChanged(FollowLikeBeanResult followLikeBeanResult) {
                ToastUtils.showLong("点赞成功");
                //更新数据
                adapter.getData().get(currentPosition).setDianzan(1);
                //单独刷新适配器
                adapter.notifyItemChanged(currentPosition);
            }
        });

        viewModel.noLikeSuccess.observe(requireActivity(), new Observer<FollowLikeBeanResult>() {
            @Override
            public void onChanged(FollowLikeBeanResult followLikeBeanResult) {
                ToastUtils.showLong("取消点赞成功");
                //更新数据
                adapter.getData().get(currentPosition).setDianzan(0);
                //单独刷新适配器
                adapter.notifyItemChanged(currentPosition);
            }
        });

        viewModel.getCommentSuccess.observe(requireActivity(), new Observer<CommentBeanResult>() {
            @Override
            public void onChanged(CommentBeanResult commentBeanResult) {
                //刷新评论的适配器
                RecyclerView rvComment = (RecyclerView) adapter.getViewByPosition(currentPosition,
                        R.id.video_rv_comment);
                rvComment.setLayoutManager(new LinearLayoutManager(getActivity()));
                commentAdapter = new CommentAdapter(commentBeanResult.getData());
                rvComment.setAdapter(commentAdapter);
            }
        });

        viewModel.sendCommentSuccess.observe(requireActivity(), new Observer<CommentBeanResult>() {
            @Override
            public void onChanged(CommentBeanResult commentBeanResult) {
                //在评论列表的第0位添加最新评论
                commentAdapter.getData().addAll(0, commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();

                //拿到评论的recyclerView,滚动到最新位置
                RecyclerView rvComment = (RecyclerView) adapter.getViewByPosition(currentPosition,
                        R.id.video_rv_comment);
                rvComment.scrollToPosition(0);

                //清理输入框的内容
                EditText editText = (EditText) adapter.getViewByPosition(currentPosition, R.id.video_ed_msg);
                editText.setText("");
            }
        });
    }

    @Override
    protected void initView() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        dataBinding.reCommondRv.setLayoutManager(layoutManager);
        dataBinding.reCommondRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                //获取当前滑动的位置
                currentPosition = layoutManager.findFirstVisibleItemPosition();
                //获取播放器
                player = (StandardGSYVideoPlayer) adapter.getViewByPosition(currentPosition, R.id.video_gsy_player);
                if (player != null) {
                    player.startPlayLogic();
                }
            }
        });
        //实现抖音的翻页效果
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(dataBinding.reCommondRv);
//        adapter = new ReCommendAdapter(videoBeanList);
        adapter = new MutableReCommendAdapter();
        adapter.getData().addAll(videoBeanList);
        dataBinding.reCommondRv.setAdapter(adapter);

        //添加点击事件组件的ID
        adapter.addChildClickViewIds(R.id.video_iv_add, R.id.video_iv_like_btn, R.id.video_iv_comment_btn,
                R.id.video_iv_close, R.id.video_iv_send, R.id.video_iv_share_btn, R.id.video_full_iv_hor,
                R.id.video_full_iv_toLive);

        //添加子控件的点击事件
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                //获取当前视频的实体类,VideoBean
                VideoBeanResult.VideoBean videoBean = (VideoBeanResult.VideoBean) adapter.getData().get(position);
                //事件处理
                switch (view.getId()) {
                    case R.id.video_iv_add:
                        addFollow(videoBean);
                        break;
                    case R.id.video_iv_like_btn:
                        likeVideo(videoBean);
                        break;
                    case R.id.video_iv_comment_btn:
                        showComment(videoBean);
                        break;
                    case R.id.video_iv_close:
                        closeComment();
                        break;
                    case R.id.video_iv_send:
                        sendComment(videoBean);
                        break;
                    case R.id.video_iv_share_btn:
                        shareVideo(videoBean);
                        break;
                    case R.id.video_full_iv_hor:
                        fullScreenPlayer(videoBean);
                        break;
                    case R.id.video_full_iv_toLive:
                        toLive(videoBean);
                        break;
                }
            }
        });
    }

    /**
     * 跳转直播间
     *
     * @param videoBean
     */
    private void toLive(VideoBeanResult.VideoBean videoBean) {
        Intent intent = new Intent(getActivity(), LiveActivity.class);
        intent.putExtra("videoBean", videoBean);
        startActivity(intent);
    }

    /**
     * 设置全屏
     *
     * @param videoBean
     */
    private void fullScreenPlayer(VideoBeanResult.VideoBean videoBean) {
        if (player != null) {
            player.setRotateViewAuto(true);//自动旋转屏幕
            player.startWindowFullscreen(getActivity(), false, true);
            player.startPlayLogic();
        }
    }

    /**
     * 友盟分享
     *
     * @param videoBean
     */
    private void shareVideo(VideoBeanResult.VideoBean videoBean) {
        //设置分享的缩略图
        UMImage umImage = new UMImage(getActivity(), videoBean.getVideomainimg());//图片地址
        umImage.compressStyle = UMImage.CompressStyle.SCALE;//压缩图片大小

        UMWeb web = new UMWeb(videoBean.getVideopath());//分享视频的地址
        web.setTitle(videoBean.getAuthname());//标题
        web.setThumb(umImage);//缩略图
        web.setDescription(videoBean.getCaption());//描述

        new ShareAction(getActivity())
                .withMedia(web)//分享内容
                .open();
    }

    /**
     * 发送评论
     *
     * @param videoBean 视频bean
     */
    private void sendComment(VideoBeanResult.VideoBean videoBean) {
        EditText sendEdit = (EditText) adapter.getViewByPosition(currentPosition, R.id.video_ed_msg);
        String sendContent = sendEdit.getText().toString();
        if (TextUtils.isEmpty(sendContent)) {
            ToastUtils.showLong("请输入文本");
            return;
        }
        viewModel.sendComment(sendContent, videoBean.getId());
    }

    /**
     * 关闭评论列表
     */
    private void closeComment() {
        View commentLayout = adapter.getViewByPosition(currentPosition, R.id.video_ll_comment);
        Animation animationOut = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_out);
        animationOut.setDuration(500);
        animationOut.setInterpolator(new AccelerateInterpolator());
        animationOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                commentLayout.setVisibility(View.GONE);
                //恢复事件传递
                dataBinding.reCommondRv.setIntercept(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        commentLayout.startAnimation(animationOut);
    }

    /**
     * 展示评论列表的方法
     *
     * @param videoBean video实体类
     */
    private void showComment(VideoBeanResult.VideoBean videoBean) {
        //拦截recyclerView的时间
        dataBinding.reCommondRv.setIntercept(false);

        //显示出评论列表
        View commentLayout = adapter.getViewByPosition(currentPosition, R.id.video_ll_comment);
        commentLayout.setVisibility(View.VISIBLE);
        //加载动画
        Animation animationIn = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_in);
        animationIn.setDuration(500);
        animationIn.setInterpolator(new AccelerateInterpolator());//加速度的插值器,越来越快
        animationIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                //加载评论列表,获取数据源
                viewModel.getCommentList(videoBean.getId());
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        //执行动画
        commentLayout.startAnimation(animationIn);
    }

    /**
     * 关注视频
     *
     * @param videoBean video实体类
     */
    private void likeVideo(VideoBeanResult.VideoBean videoBean) {
        if (videoBean.getDianzan() == 0) {
            //代表未点赞
            viewModel.likeVideo(videoBean.getId());
        } else {
            viewModel.noLikeVideo(videoBean.getId());
        }
    }

    /**
     * 添加关注
     *
     * @param videoBean
     */
    private void addFollow(VideoBeanResult.VideoBean videoBean) {
        viewModel.followAuth(videoBean.getAuthname());
    }

    @Override
    protected Class<VideoViewModel> getViewModel() {
        return VideoViewModel.class;
    }
}